package icom.acm.net;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 
 * @author shench
 * 邮箱发送
 */
public class SendMail {
	private String host = "smtp.gmail.com"; // 邮箱服务器
	private String headName = "Helle,Coding!";
	private String headValue = "欢迎注册";
	private String from;		// 发件人
	private String to;		// 收件人
	private String copyTo;	// 抄送
	private String bcc;		// 暗送
	private String subject;	// 主题
	private String body;	// 内容
	private String personalName = "Coding";
	private Authenticator auth;	// 服务器认证
	
	public SendMail(){}
	
	public SendMail(String value, String to, String subject, String body){
		this("smtp.gmail.com", "hello.coding@gmail.com", "codingthefuture",
				value, to, subject, body);
	}
	
	public SendMail(String host, String username, String password,
			String value,
			String to, String subject, String body){
		/*from = "hello.coding@gmail.com";
		to = "acmersch@163.com";
		subject = "欢迎注册";
		body = "欢迎注册成功";*/		
		this.host = host;
		auth = new Email_Autherticator(username, password);
		this.headValue = value;
		this.from = username;
		this.to = to;
		this.subject = subject;
		
		StringBuffer content = new StringBuffer();
		content.append("<html>");
		content.append("<head>");
		content.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		content.append("</head>");
		content.append("<body>");
		content.append(body);
		content.append("</body>");
		content.append("</html>");	
		//content.append(body);
		this.body = new String(content);
		
		
	}
	/**
	 * 设置系统环境
	 */
	private Properties initProp(){
		Properties props = new Properties(); // 获取系统环境
        // 进行邮件服务器用户认证
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.auth", "true");
      props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
      props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
      props.setProperty("mail.smtp.port", "465"); 
      props.setProperty("mail.smtp.socketFactory.port", "465");
      return props;
	}
	/**
	 * 设置消息文件
	 * @param props
	 * @return
	 */
	private MimeMessage setMessage(Properties props){
		Session session = Session.getDefaultInstance(props, auth);            
        // 设置session,和邮件服务器进行通讯。
        MimeMessage message = new MimeMessage(session);
        // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
        try {
			message.setSubject(subject);// 设置邮件主题            
			message.setContent(body, "text/html;charset=utf-8"); // 设置邮件正文
	        message.setHeader(headName, headValue); // 设置邮件标题
	        message.setSentDate(icom.acm.util.DateUtil.now()); // 设置邮件发送日期
	        
	        Address address = new InternetAddress(from, personalName);
	        message.setFrom(address); // 设置邮件发送者的地址
	        Address toAddress = new InternetAddress(to); // 设置邮件接收方的地址
	        message.addRecipient(Message.RecipientType.TO, toAddress);
		} catch (MessagingException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} 
        return message;
	}
	
	/**
	 * 发送邮件
	 */
	public boolean send(){
		if (!check(to)){
			return false;
		}

		Properties props = initProp();            
		MimeMessage message = setMessage(props);            
        try {
        	// 发送邮件
			Transport.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		} 
        System.out.println("send ok!");        
        return true;
	}
	
	public boolean check(String mail){  
	    String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";  
	    Pattern p = Pattern.compile(regex);  
	    Matcher m = p.matcher(mail);  
	    return m.find();  
	}  
	
	 public static void main(String[] args){
			String s = "http:localhost:8080/acmwb/UserActivate_activate?" +
			"ua.UA_U_ID=" + 00 +
			"&ua.UA_KEY=fjlskajdflksa";
						
			SendMail sm = new SendMail("注册成功", "acmersch@163.com", "成功注册Coding3", 
					"注册Coding成功,请点下面链接进行激活，如果不能点击，复制链接浏览即可:\n"+
					"<a href='" + s + "'>" + s + "</a>"+
					"<font size='6'>请在24小时内激活!</font>");
			sm.send();		
	 }
}
